package com.jwong.auth.server.sms;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @description: 添加短信验证 TokenGranter
 * @author:JWong
 */
public final class OverrideTokenGranterConfigurer {

    public static TokenGranter tokenGranter(AuthorizationServerEndpointsConfigurer endpoints,
                                            AuthenticationManager authenticationManager) {

        // 获取原 tokenGranters
        TokenGranter tokenGranter = endpoints.getTokenGranter();
        List<TokenGranter> tokenGranters = new ArrayList<>(Collections.singletonList(tokenGranter));

        OAuth2RequestFactory requestFactory = endpoints.getOAuth2RequestFactory();
        ClientDetailsService clientDetailsService = endpoints.getClientDetailsService();
        AuthorizationServerTokenServices tokenServices = endpoints.getTokenServices();

        // 添加自定义短信验证码授权模式, sms_code需要authenticationManager，必须保证其不为空
        if (authenticationManager != null) {
            SmsCodeTokenGranter smsCodeTokenGranter = new SmsCodeTokenGranter(authenticationManager,
                    tokenServices, clientDetailsService, requestFactory);
            tokenGranters.add(smsCodeTokenGranter);
            return new CompositeTokenGranter(tokenGranters);
        }

        return tokenGranter; // 返回原TokenGranter
    }

}
